from rest_framework import serializers
from .models import Banner, Category, Goods, Cart


class BannerSerializer(serializers.ModelSerializer):
    """轮播图序列化器"""
    class Meta:
        model = Banner
        fields = ['id', 'image_url', 'link']


class CategorySerializer(serializers.ModelSerializer):
    """分类序列化器"""
    class Meta:
        model = Category
        fields = ['id', 'name', 'icon_url']


class SubCategorySerializer(serializers.ModelSerializer):
    """子分类序列化器"""
    class Meta:
        model = Category
        fields = ['id', 'name']


class CategoryWithSubSerializer(serializers.ModelSerializer):
    """带子类别的分类序列化器"""
    sub_categories = SubCategorySerializer(many=True, read_only=True)

    class Meta:
        model = Category
        fields = ['id', 'name', 'sub_categories']


class GoodsSerializer(serializers.ModelSerializer):
    """商品序列化器"""
    class Meta:
        model = Goods
        fields = ['id', 'name', 'image_url', 'original_price', 'current_price', 'sales', 'is_hot']


class GoodsListSerializer(serializers.ModelSerializer):
    """商品列表序列化器"""
    class Meta:
        model = Goods
        fields = ['id', 'name', 'image_url', 'current_price', 'sales', 'spec']


class CartSerializer(serializers.ModelSerializer):
    """购物车序列化器"""
    goods = GoodsSerializer(read_only=True)
    goods_id = serializers.IntegerField(write_only=True)

    class Meta:
        model = Cart
        fields = ['id', 'goods', 'goods_id', 'num', 'spec', 'selected', 'add_time']
        read_only_fields = ['add_time']

    def create(self, validated_data):
        user = self.context['request'].user
        goods_id = validated_data.pop('goods_id')
        num = validated_data.get('num', 1)
        spec = validated_data.get('spec', '')

        # 检查商品是否存在
        try:
            goods = Goods.objects.get(id=goods_id)
        except Goods.DoesNotExist:
            raise serializers.ValidationError({'goods_id': '商品不存在'})

        # 检查购物车中是否已存在该商品
        cart_item, created = Cart.objects.get_or_create(
            user=user,
            goods=goods,
            spec=spec,
            defaults={'num': num, 'selected': True}
        )

        # 如果已存在，则增加数量
        if not created:
            cart_item.num += num
            cart_item.save()

        return cart_item

    def update(self, instance, validated_data):
        # 更新数量或选中状态
        if 'num' in validated_data:
            instance.num = validated_data['num']
        if 'selected' in validated_data:
            instance.selected = validated_data['selected']
        instance.save()
        return instance